<template>
  <div id="excel">
    <el-button
      style="margin-left: 10px"
      @click="exportExl"
      :size="size"
      :disabled="disabledExport"
      v-if="!hiddenExport">
      导出数据
    </el-button>
    <el-button
      :size="size"
      @click="$refs['upload'].click()"
      :disabled="disabledImport"
      :loading="loading.exportBtn"
      v-if="!hiddenImport">
      导入数据
      <input style="display: none" ref="upload" type="file" @change="importsExl"
             accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
    </el-button>
  </div>
</template>

<script>
  import { exports, imports } from './excel'

  export default {
    name: "index",
    components: {},
    props: {
      disabledExport: { type: Boolean, default: false },
      disabledImport: { type: Boolean, default: false },
      hiddenExport: { type: Boolean, default: false },
      hiddenImport: { type: Boolean, default: false },
      exportTitle: { default: '数据列表' }, // 导出标题
      exportBtnText: { default: '导出数据' },// 导出按钮文字
      importBtnText: { default: '导入数据' },// 导入按钮文字
      size: {
        default: 'small', // medium / small / mini
        type: String
      },
      header: { // 导入导出时的表格标题
        type: Array,
        required: true
      },
      data: { // 导出数据
        type: Array,
        default: [],
        required: true
      },
      beforeExport: { // 导出之前的方法
        type: Function,
      },
      onSuccess: { // 导入成功时的方法
        type: Function
      }
    },
    data() {
      return {
        loading: { exportBtn: false },
        ex: {
          importData: []
        }
      }
    },
    watch: {
      'ex.importData': {
        handler: async function () {
          console.log('导入数据：', this.ex.importData);
          this.onSuccess && this.onSuccess(this.ex.importData);
        },
        deep: true
      }
    },
    created() {
    },
    methods: {
      // 导入
      importsExl() {
        this.loading.exportBtn = true;
        let rABS = false //是否将文件读取为二进制字符串
          , f = this.file = event.currentTarget.files[0] // 得到当前上传的文件
          , reader = new FileReader()
        ;
        try {
          imports.call(this, {data: f, header: this.header});
          rABS ? reader.readAsArrayBuffer(f) : reader.readAsBinaryString(f);
        } catch ({message}) {
          this.$message.error(message);
        } finally {
          this.loading.exportBtn = false;
          this.$refs['upload'].value = null;
        }
      },

      // 导出
      async exportExl() {
        try {
          // 等待数据准备完毕
          this.beforeExport && await this.beforeExport(); // 该函数也需要被 async await 修饰
          exports({data: this.data, header: this.header, title: this.exportTitle})
        } catch (err) {
          console.error(err)
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  #excel {
    display: inline-block;
  }
</style>
